//
//  CYLoginHttpTool.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/27.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYLoginHttpTool.h"
#import "CYURL.h"
#import "MJExtension.h"
#import "CYJumpsTool.h"
#import "CYJsonInfo.h"
#import "CYCompanyRegParam.h"
#import "CYCompanyUserTool.h"
#import "CYCompanyUserModel.h"

#define CYUserFile [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.data"]

@implementation CYLoginHttpTool

+ (void)regeditWithParams:(NSDictionary *)params success:(HttpRequestSuccess)success failure:(HttpRequestFailure)failure {
    CYLog(@"params:%@", params);
    [CYHttpTool postWithURL:[CYURL RegeditPath] params:params success:^(id json) {
        if (success) {
            success(json);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)loginWithUserName:(NSString *)username andPassword:(NSString *)password success:(HttpRequestSuccess)success failure:(HttpRequestFailure)failure {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"phone"] = username;
    params[@"userPassword"] = password;
    [CYHttpTool postWithURL:[CYURL LoginPath] params:params success:^(id json) {
        if (success) {
            success(json);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)sendSMSWithPhone:(NSString *)phone success:(HttpRequestSuccess)success failure:(HttpRequestFailure)failure {
    NSDictionary *params = @{@"phone": phone};
    CYLog(@"phone:%@", phone);
    [CYHttpTool postWithURL:[CYURL SendSmsPath] params:params success:^(id json) {
        if (success) {
            success(json);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)sendSMSWithUsername:(NSDictionary *)username success:(HttpRequestSuccess)success failure:(HttpRequestFailure)failure {
//    NSDictionary *params = @{@"userName":username,@"type":@"01",@"channelID":@"12003"};
    NSDictionary *params = [[NSDictionary alloc]init];
    [CYHttpTool getWithURL:@"https://login.10086.cn/sendRandomCodeAction.action" params:params success:^(id json) {
        if (success) {
            success(json);
            
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)checkUserNameWithUserName:(NSString *)userName success:(HttpRequestSuccess)success failure:(HttpRequestFailure)failure {
    NSDictionary *params = @{@"phone": userName};
    [CYHttpTool postWithURL:[CYURL CheckUserNamePath] params:params success:^(id json) {
        if (success) {
            success(json);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)findPasswordWithPhone:(NSString *)phone andPhoneCode:(NSString *)phoneCode success:(HttpRequestSuccess)success failure:(HttpRequestFailure)failure {
    NSDictionary *params = @{@"phone": phone, @"phoneCode": phoneCode};
    [CYHttpTool postWithURL:[CYURL findPasswordPath] params:params success:^(id json) {
        if (success) {
            success(json);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark - 企业
/**
 *  企业注册
 */
+ (void)regeditCompanyWithParams:(CYCompanyRegParam *)params success:(void(^)(NSString *message))success failure:(HttpRequestFailure1)failure {
    [CYHttpTool postWithURL:[CYURL shared].reg params:params.keyValues success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, nil);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"企业注册错误: %@", error);
        if (failure) {
            failure(nil, error);
        }
    }];
}
/**
 *  验证租车企业是否已经存在
 */
+ (void)checkCarCompanyUserWithCompanyAccount:(NSString *)carCompanyAccount success:(void(^)())success failure:(HttpRequestFailure1)failure {
    NSDictionary *params = @{@"carCompanyAccount": carCompanyAccount};
    [CYHttpTool postWithURL:[CYURL shared].checkCarCompanyUser params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success();
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, nil);
            }
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(nil, error);
        }
    }];
}
/**
 *  企业登陆
 */
+ (void)companyLoginWithUserName:(NSString *)username andPassword:(NSString *)password success:(void(^)(NSString *message))success failure:(HttpRequestFailure1)failure {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"carCompanyAccount"] = username;
    params[@"carCompanyPassword"] = password;
    [CYHttpTool postWithURL:[CYURL shared].login params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            CYCompanyUserModel *model = [CYCompanyUserModel objectWithKeyValues:jsonInfo.data];
            [CYCompanyUserTool saveUserLoginInfo:model];
            if (success) {
                success(jsonInfo.message);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, nil);
            }
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(nil, error);
        }
    }];
}

#pragma mark -
/**
 *  保存用户登录信息
 */
+ (BOOL)saveUserLoginInfo:(CYUser *)user {
    CYUserData *userData = [[CYUserData alloc] init];
    userData.user = user;
    userData.loginInTime = [NSDate date];
    NSTimeInterval interval = 24*60*60*90;
    userData.expiresTime = [[NSDate alloc] initWithTimeIntervalSinceNow:interval];//获取90天后的日期
//    CYLog(@"保存用户登录信息:%@", userData.user.examineStatus);
    //序列化
    
    //登录成功将用户信息保存到沙河
//    NSUserDefaults *deft = [NSUserDefaults standardUserDefaults];
//    [deft setObject:user.phone forKey:CYUserNameKey];
//    [deft setObject:user.userPassword forKey:CYPasswordKey];
//    [deft synchronize];
    
    BOOL result = [NSKeyedArchiver archiveRootObject:userData toFile:CYUserFile];
    if (result) {
        return YES;
    }
    return NO;
}

/**
 *  更新用户信息
 */
+ (BOOL)updateUserData:(CYUser *)user {
    //取出旧数据2
    CYUserData *userData = [self userData];
    if (userData && user) {
        userData.user = user;
//        CYLog(@"更新用户信息:%@", user.examineStatus);
        //序列化
        [NSKeyedArchiver archiveRootObject:userData toFile:CYUserFile];
        return YES;
    }
    return NO;
}

/**
 *  获取用户信息
 */
+ (CYUserData *)userData {
    // 取出账号
    CYUserData *account = [NSKeyedUnarchiver unarchiveObjectWithFile:CYUserFile];
    // 判断账号是否过期
    NSDate *now = [NSDate date];
    if ([now compare:account.expiresTime] == NSOrderedAscending) { // 还没有过期
        return account;
    } else { // 过期
        [self logout];
        return nil;
    }
}

/**
 *  清除用户信息
 */
+ (BOOL)isClearUserData {
    NSFileManager * fileManager = [[NSFileManager alloc]init];
    if ([fileManager isDeletableFileAtPath:CYUserFile]) {
        [fileManager removeItemAtPath:CYUserFile error:nil];
        return YES;
    }
    return NO;
}

+ (BOOL)logout {
    //登出后清除本地归档信息
    BOOL result = [self isClearUserData];
    if (result) {
        //登出后清除本地归档信息
        NSUserDefaults *deft = [NSUserDefaults standardUserDefaults];
        [deft removeObjectForKey:CYUserNameKey];
        [deft removeObjectForKey:CYPasswordKey];
        [deft synchronize];
        //发出登出的通知
        [CYNotificationCenter postNotificationName:nCYLogout object:nil userInfo:nil];
        return YES;
    }
    return NO;
}

+ (void)logoutWithController:(UIViewController *)con {
    [self logout];
    [CYJumpsTool jumpToLogin:con];
}
@end
